<?php

/**
 * This is the model class for table "first_order".
 *
 * The followings are the available columns in table 'first_order':
 * @property string $order_id
 * @property string $verify_status
 * @property string $payment_status
 */
class FirstOrder extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return FirstOrder the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'first_order';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('order_id', 'required'),
			array('order_id, payment_status, payment_id', 'length', 'max'=>10),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('order_id, payment_status', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'order_history' => array(self::BELONGS_TO, 'OrderHistory', 'order_id')
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'order_id' => 'Order',
			'payment_status' => 'Payment Status',
			'payment_id' => 'Payment ID'
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('order_id',$this->order_id,true);
		$criteria->compare('payment_status',$this->payment_status,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	/**
	 * 读取待审核的首次订单数
	 */
	public static function getNumToVerify() {
		$n = Yii::app()->params['daysAfterFirstOrder'];
		$date = date('Y-m-d', strtotime("-$n days"));
		$sql = "SELECT count(*) FROM first_order f, order_history h WHERE f.order_id=h.order_id AND verify_status=0 AND adddate<='$date'";
		return Yii::app()->db->createCommand($sql)->queryScalar();
	}
}